package com.bio.jsf;

import java.io.File;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

@ManagedBean(name = "documentsController")
@ViewScoped
public class DocumentsController implements Serializable {

    private TreeNode root;

    public DocumentsController() {
        root = new DefaultTreeNode("root", null);
        File dir = new File(".");

        searchInTextFiles(dir);

    }

    public void searchInTextFiles(File dir) {
        String[] a = dir.list();
        for (String f : a) {
            File file = new File(f);
            if (file.isDirectory()) {
                searchInTextFiles(file);
            } else {
                searchInFile(file);
            }
        }
    }
    TreeNode previos;
    TreeNode next;

    private void searchInFile(File f) {
        if (previos != null) {
            if (f.getAbsolutePath().length() > ((File) previos.getData()).getAbsolutePath().length()) {
                next = new DefaultTreeNode(new File(f.getAbsolutePath()), previos);
            } else {
                previos = new DefaultTreeNode(new File(f.getAbsolutePath()), next);
            }
        }else{
            TreeNode documents = new DefaultTreeNode(new File(f.getAbsolutePath()), root);
            previos = documents;
        }

        
    }

    public TreeNode getRoot() {
        return root;
    }
}
